package com.cmw.core.kit.email.commonemail;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

import com.cmw.core.kit.email.EmailAdapter;
import com.cmw.core.kit.email.EmailCallback;
import com.cmw.core.kit.email.EmailInter;
import com.cmw.core.kit.email.model.SendEmailModel;
import com.cmw.core.util.DateUtil;
import com.cmw.core.util.StringHandler;

/**
 * 利用 Common-Email 包发送邮件
 * @author chengmingwei
 * @date 2016-06-30 9:49
 */
public class CmEmailManager extends EmailAdapter {
	static Logger logger = Logger.getLogger(CmEmailManager.class);
	
	//Email instance = new SimpleEmail();
	HtmlEmail instance = null;
	
	@Override
	public void send(String toEmail, String title, String content) throws EmailException {
		init();
		Date startDate = new Date(System.currentTimeMillis());
		instance.addTo(toEmail);
		instance.setSubject(title);
		instance.setHtmlMsg(content);
		instance.setCharset("UTF-8");
		instance.setTextMsg("Your email client does not support HTML messages");
		instance.send();
		Date endDate = new Date(System.currentTimeMillis());
		long time = endDate.getTime() - startDate.getTime();
		time = time / 1000;
		logger.info("向“"+toEmail+"”发送邮件成功,用时"+time+"秒。");
	}
	

	public void send(HtmlEmail emailInstance,String toEmail, String title, String content) throws EmailException {
		Date startDate = new Date(System.currentTimeMillis());
		emailInstance.addTo(toEmail);
		emailInstance.setSubject(title);
		emailInstance.setHtmlMsg(content);
		emailInstance.setCharset("UTF-8");
		emailInstance.setTextMsg("Your email client does not support HTML messages");
		emailInstance.send();
		Date endDate = new Date(System.currentTimeMillis());
		long time = endDate.getTime() - startDate.getTime();
		//time = time / 1000;
		logger.info("向“"+toEmail+"”发送邮件成功,用时"+time+"毫秒。");
	}
	
	private void init() throws EmailException{
		if(null != instance) return;
		instance = new HtmlEmail();
		instance.setHostName(smtpHost);
		instance.setSmtpPort(smtpPort);
		instance.setAuthenticator(new DefaultAuthenticator(account, pwd));
		instance.setSSLOnConnect(ssl);
		instance.setFrom(formEmail);
	}
	
	@Override
	public void send(List<SendEmailModel> semailList) throws EmailException {
		if(null == semailList || semailList.size() == 0) throw new EmailException("批量发送邮件时，参数：semailList 不能为空!");
		new Thread(new EmailTask(semailList, null)).start();
	}
	

	@Override
	public void send(List<SendEmailModel> semailList, EmailCallback callback)
			throws EmailException {
		if(null == semailList || semailList.size() == 0) throw new EmailException("批量发送邮件时，参数：semailList 不能为空!");
		new Thread(new EmailTask(semailList, callback)).start();
	}
	
	
	class EmailTask implements Runnable{
		List<SendEmailModel> semailList = null;
		List<SendEmailModel> failure_semailList = new CopyOnWriteArrayList<SendEmailModel>(); //记录发送失败的邮件
		EmailCallback callback = null;
		public EmailTask(List<SendEmailModel> semailList, EmailCallback callback) {
			this.semailList = semailList;
			this.callback = callback;
		}

		@Override
		public void run() {
			if(null == semailList || semailList.size() == 0) return;
			for(SendEmailModel model : semailList){
				sendEmail(model);
			}
			
			/**------- 发送失败的邮件 ------**/
			if(null != failure_semailList && failure_semailList.size() > 0){
				for(SendEmailModel model : failure_semailList){
					sendEmail(model);
				}
			}
		}

		private void sendEmail(SendEmailModel model) {
			String toEmail = model.getTo();
			String title = model.getTitle();
			String content = model.getContent();
			int xstatus = SendEmailModel.XSTATUS_SUCCESS;
			try {
				if(!StringHandler.isValidStr(toEmail)) return;
				HtmlEmail instance = new HtmlEmail();
				instance.setHostName(smtpHost);
				instance.setSmtpPort(smtpPort);
				instance.setAuthenticator(new DefaultAuthenticator(account, pwd));
				instance.setSSLOnConnect(ssl);
				instance.setFrom(formEmail);
				send(instance, toEmail, title, content);//发完一封睡眠半秒
			} catch (EmailException e) {
				xstatus = SendEmailModel.XSTATUS_FAILURE;
				e.printStackTrace();
				logger.info("向“"+toEmail+"”发送邮件失败,已放入重发消息对列，等待下次重发,时间："+(DateUtil.dateFormatToStr(DateUtil.DATE_TIME_FORMAT, new Date(System.currentTimeMillis())))+"。");
			}
			model.setXstatus(xstatus);
			if(null != callback) callback.execute(model);
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public static void main(String[] args){
		EmailInter emailMgr = new CmEmailManager();
		try {
			//emailMgr.send("869693674@qq.com", "测试", "多喝水");
			//emailMgr.send("340360491@qq.com", "测试", "<a href='http://www.baidu.com'>多喝水</a>");
			List<SendEmailModel> emailList = new ArrayList<SendEmailModel>();
//			emailList.add(new SendEmailModel("869693674@qq.com","测试","<a href='http://www.baidu.com'>多喝水</a>"));
//			emailList.add(new SendEmailModel("340360491@qq.com","测试","<a href='http://www.baidu.com'>多喝水</a>"));
//			emailList.add(new SendEmailModel("419378696@qq.com","测试","<a href='http://www.baidu.com'>多喝水</a>"));
//			emailList.add(new SendEmailModel("2572321858@qq.com","测试","<a href='http://www.baidu.com'>多喝水</a>"));
			
//			emailList.add(new SendEmailModel("869693674@qq.com","试","<a href='http://www.baidu.com'>多吃饭</a>"));
			emailList.add(new SendEmailModel("340360491@qq.com","测试","<a href='http://www.baidu.com'>多吃饭</a>"));
//			emailList.add(new SendEmailModel("419378696@qq.com","测试","<a href='http://www.baidu.com'>多吃饭</a>"));
//			emailList.add(new SendEmailModel("2572321858@qq.com","测试","<a href='http://www.baidu.com'>多吃饭</a>"));
			emailMgr.send(emailList);
			System.out.println("====================");
		} catch (EmailException e) {
			e.printStackTrace();
		}
	}


	@Override
	public void sendSelf(String content) throws EmailException {
		String title = "系统邮件";
		String sysEmail = resourceObj.getString("mail.sys.account");
		System.out.println("sysEmail="+sysEmail);
		send(sysEmail, title, content);
	}



	
}
